import User from '../models/user';
import { getRedisUserTokenKey } from '../common/constant';

export default function tokenAuth() {
  return async (ctx, next) => {
    const { token } = ctx.request.body;

    if (typeof token !== 'string' || token === '') {
      ctx.throw('no_token');
      return null;
    }

    const result = await ctx.redis.get(getRedisUserTokenKey(token));

    if (result) {
      ctx.viewer = await User.findById(result);
      return next();
    }

    ctx.throw('invalid_token');
    return null;
  };
}
